#!/bin/sh
#
# The initial system boot script.  This only does one thing: try to find
# the root filesystem and mount it if possible.
#
exec 9>&1 >/dev/kmsg 2>&1

echo "---- initramfs ('$0')"
echo "To bypass this script, use rdinit=/bin/sh"

# Mount /dev, /proc, /sys, etc
/mounts-sys

. /helpers.sh
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

trap 'log FATAL - INIT EXITED - Rebooting.; reboot >&9 2>&1 9>&-' EXIT


# Initialize any loadable driver modules
for d in /lib/modules/*.ko /lib/modules/*/*.ko; do
  [ -e "$d" ] && insmod $d
done

# Mount /rootfs and possibly set INIT
. /mounts-root || die "couldn't mount root filesystems"

# Run anything that needs to finish before init
# Pass in paths for $PLATFORM and $DEBUG
/preinit "/rootfs/etc/platform" "/rootfs/tmp/DEBUG"

log 'Looking for init in rootfs.  To bypass this, use init=/bin/sh'
for init in "$INIT" /sbin/init /linuxrc /bin/sh; do
  [ -n "$init" ] || continue
  log "Trying '/rootfs$init'"
  [ -x "/rootfs$init" ] || continue
  case "$init" in
    /sbin/init) args=1 ;;
    *) args= ;;
  esac
  cd /rootfs
  [ "$init" = "$INIT" ] && exec >&9 2>&1  # probably a shell; bring back tty
  exec 9>&-   # close fd to console
  exec switch_root /rootfs "$init" $args
done

die "couldn't switch to root filesystem"
